package com.mmd.intercepter;


import com.alibaba.fastjson.JSON;
import com.mmd.bean.CODE;
import com.mmd.bean.UserLoginContext;
import com.mmd.exception.GameException;
import com.mmd.redis.RedisKey;
import com.mmd.redis.RedisManager;
import com.mmd.utils.CookieTools;
import com.mmd.utils.Validator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * admin登录拦截器
 */
public class AdminInterceptor implements HandlerInterceptor {

	private static Logger LOGGER = LoggerFactory.getLogger(AdminInterceptor.class);
	
	private static ThreadLocal<UserLoginContext> userLoginContext = new ThreadLocal<UserLoginContext>();

	/**
	 * 获得当前登录用户信息
	 * 
	 */
	public static UserLoginContext getUserLoginContext() {
		if (userLoginContext.get() == null) {
			throw new GameException(CODE.NOTLOGIN);
		}
		return userLoginContext.get();
	}

	public static void clearUserLoginContext() {
		userLoginContext.set(null);
	}
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws IOException {
		LOGGER.info("host:{}, localName:{}, url:{}",request.getRemoteHost(),request.getLocalName(),request.getRequestURL());
		response.setHeader("Content-type", "text/html;charset=UTF-8");
		userLoginContext.set(null); // 先清掉登录态
		Cookie tokenCookie = CookieTools.getCookieByName(request, "adminToken");
		//前端隐藏传输，at为管理后台的的token
		try {
			UserLoginContext loginInfo = validatorLogin(tokenCookie);
			LOGGER.info("loginInfo==>{}",loginInfo);
				
			userLoginContext.set(loginInfo);
			RedisManager.set(RedisKey.ADMIN_TOKEN + tokenCookie.getValue(), loginInfo, 6000);
			CookieTools.addCookie(response, "adminToken", tokenCookie.getValue(), 6000);
			RedisManager.set(RedisKey.USER_INFO + loginInfo.getUid(), loginInfo, 6000);
			return true;
		} catch (GameException e) {
			LOGGER.error("登录异常: {}, {}",e.getMessage(),e);
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("code", e.getCode());
			map.put("desc", e.getMsg());
			map.put("tid", UUID.randomUUID().toString());
			response.getWriter().write(JSON.toJSONString(map));
			return false;
		}
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}

	/**
	 * 检查登录，登录成功返回userId，否则返回null
	 * 
	 * @param tokenCookie
	 * @return
	 */
	private UserLoginContext validatorLogin(Cookie tokenCookie) {
		if (tokenCookie == null)
			throw new GameException(CODE.NOTLOGIN);
		String ctoken = tokenCookie.getValue();
		Object obj = RedisManager.get(RedisKey.ADMIN_TOKEN + ctoken);
		if (!Validator.isNotNullOrEmpty(obj))
			throw new GameException(CODE.NOTLOGIN);
		UserLoginContext user = (UserLoginContext) obj;
		if (Validator.isNullOrEmpty(user))
			throw new GameException(CODE.NOTLOGIN);
		return user;
	}
	
}